﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using umbraco.BusinessLogic.Actions;
using umbraco.cms.businesslogic.web;
using umbraco.cms.businesslogic.property;
using umbraco.interfaces;
using umbraco.NodeFactory;
using System.Net.Mail;

namespace ExtendedWorkFlow.Commands
{

    public class Notification : IExtendedWorkFlowCommand
    {

        public bool RunCommand(string Parameters, Node Command, WorkFlow WorkFlow)
        {
            try
            {
                // Get all parameters into readable collection
                ParameterCollection colParameters = Functions.GetParameters(Parameters);

                // Make sure the mail message is disposed
                using (MailMessage objMailMessage = new MailMessage())
                {

                    if (colParameters["subject"].Value == string.Empty &&
                        colParameters["to"].Value == string.Empty &&
                        colParameters["from"].Value == string.Empty)
                        throw new MissingFieldException("You must specify subject, to and from parameters");

                    // Mail message
                    objMailMessage.From = new MailAddress(colParameters["from"].Value);
                    objMailMessage.Subject = colParameters["subject"].Value;
                    objMailMessage.IsBodyHtml = false;

                    // Recipients
                    foreach (string strAddress in colParameters["to"].Value.Split(";".ToArray()))
                        objMailMessage.To.Add(new MailAddress(strAddress));

                    string strBody = @"
Notification that ExtendedWorkFlow has performed an action and the command was [" + Command.Name + @"]

Document [" + WorkFlow.Document.Text + @"]

If you need to check if all actions and/or commands ran successfully please login to the Umbraco administration
and check the documents 'audit trail'.";

                    if (colParameters["body"].Value != string.Empty)
                        strBody += @"

" + colParameters["body"].Value;

                    objMailMessage.Body = strBody;

                    SmtpClient objClient = new SmtpClient();
                    objClient.Send(objMailMessage);

                    return true;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return false;
        }

    }

}